import os
import json
import shutil
import time

# import util
from . import util
import sys

def xcode_build(proj_path, proj_name, target_name=None, schema_name=None, configuration="Debug", **keywords):
    """
    xcode执行编译
    :param proj_path:
    :param proj_name:
    :param target_name:
    :param schema_name:
    :param configuration:
    :param keywords:
    :return:
    """
    #工程名
    if not os.path.exists(proj_path):
        return

    command = "xcodebuild build"
    if ".xcworkspace" in proj_name:
        command = command + " -workspace " + proj_name
        proj_name = proj_name.split(".xcworkspace")[0]
    elif ".xcodeproj" in proj_name:
        command = command + " -project " + proj_name
        proj_name = proj_name.split(".xcodeproj")[0]

    if target_name is None:
        target_name = proj_name
    # #target
    # command = command + " -target " + target_name
    if schema_name is None:
        schema_name = target_name
    #schema
    command = command + " -scheme " + schema_name
    #
    command = command + " -configuration " + configuration
    #print(command)

    return util.excute_shell(command, path=proj_path, pipe_out=False)

def xcode_speed_package(env_config_path, ipa_save_path=None):
    """
    xcode快速取包
    :return:
    """
    if env_config_path is None:
        print("python日志 xcode编译环境参数文件不存在")
        return
    with open(env_config_path, "r") as f:
        env_config_data = json.load(f)
        build_dir_path = env_config_data["BUILD_DIR"]
    app_name = env_config_data["PRODUCT_NAME"]
    app_ext = ".app"
    app_path = os.path.join(build_dir_path, "Build/Products/Debug-iphoneos", app_name+app_ext)
    env_dir = os.path.dirname(env_config_path)
    temp_path = env_dir + "/temp"
    payload_path = temp_path + "/Payload"
    payload_app_path = payload_path + "/" + app_name+app_ext
    if os.path.exists(temp_path):
        shutil.rmtree(temp_path)
        time.sleep(1)
    os.makedirs(temp_path)
    shutil.copytree(app_path, payload_app_path)
    zip_path = shutil.make_archive(payload_path, "zip", temp_path)
    if ipa_save_path is None:
        ipa_save_path = temp_path+"/"+app_name+".ipa"
    iap_path = shutil.move(zip_path, ipa_save_path)
    if os.path.exists(payload_path):
        shutil.rmtree(payload_path)
    if os.path.exists(zip_path):
        shutil.rmtree(zip_path)
    return iap_path

def xcode_get_build_env(save_path=None):
    """
    读取xcode编译时的环境参数
    :param save_path:
    :return:
    """
    if save_path is None:
        save_path = os.getcwd() + "/build_env_config.json"
    needConfig = {}
    product_name = os.getenv("PRODUCT_NAME")
    build_dir_path = os.getenv("BUILD_DIR")
    if build_dir_path is None: return
    build_str_index = build_dir_path.find("Build/")
    if build_str_index is not None:
        build_dir_path = build_dir_path[0:build_str_index]
        needConfig["BUILD_DIR"] = build_dir_path
    needConfig["PRODUCT_NAME"] = product_name
    with open(save_path, "w") as f:
        json.dump(needConfig, f)



if __name__ == "__main__":
    """
    命令行格式
    第一个参数 函数名
    其余按顺序存入函数需要的参数
    """
    args = sys.argv[1:]
    if len(args) == 0:
        sys.exit("参数缺失")
    method = args[0]
    args = args[1:]
    print("python日志 xcode.py文件执行命令行 method:{}, args:{}".format(method, args))

    if method == "xcode_get_build_env":
        xcode_get_build_env(args[0] if len(args) > 0 else None)
    elif method == "xcode_build":
        if len(args) > 1:
            proj_path = args[0]
            proj_name = args[1]
            xcode_build(proj_path, proj_name)
    elif method == "xcode_speed_package":
        ipa_save_path = None
        if len(args) > 1:
            ipa_save_path = args[1]
        xcode_speed_package(args[0] if len(args) > 0 else None, ipa_save_path)


    pass